package com.xiaolin.sports.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.aliyun.mns.model.TopicMessage;
import com.xiaolin.sports.aliyun.mns.SMSMessageUtil;
import com.xiaolin.sports.common.RspResult;
import com.xiaolin.sports.common.enums.Status;
import com.xiaolin.sports.model.SmsValidateCode;
import com.xiaolin.sports.service.ISmsValidateCodeService;
import com.xiaolin.sports.utils.RequestUtil;

@Controller
public class SmsController extends BaseController {

	private Logger logger = LoggerFactory.getLogger(SmsController.class);
	
	@Autowired
	private ISmsValidateCodeService smsVaildateCodeService;
	
	@RequestMapping("sendSms")
	public @ResponseBody Object sendSms(String mobile) {
		try {
			String ip = RequestUtil.getClientIp(request);
			int count = smsVaildateCodeService.selectCountForDay(ip);
			if(count >= 5) {
				return new RspResult(Status.SMS_SEND_LIMIT);
			}
			int code = (int)(Math.random()*9000 + 1000);
			SmsValidateCode record = new SmsValidateCode();
			record.setCode(String.valueOf(code));
			record.setIp(ip);
			record.setMobile(mobile);
			TopicMessage message = SMSMessageUtil.sendSms(mobile, record.getCode());
			if(message != null && message.getMessageId() != null) {
				smsVaildateCodeService.insertSelective(record);
				return new RspResult(Status.SUCCESS);
			}
		} catch (Exception e) {
			logger.error("----sendSms error={}", e);
		}
		return new RspResult(Status.FAIL);
	}
	
	@RequestMapping("smsVaild")
	@ResponseBody Object smsVaild(SmsValidateCode code) {
		try {
			int count = smsVaildateCodeService.isValid(code);
			if(count > 0) {
				return new RspResult(Status.SUCCESS);
			}
			return new RspResult(Status.SMS_VAILD_FAIL);
		} catch (Exception e) {
			logger.error("----smsVaild error={}", e);
		}
		return new RspResult(Status.FAIL);
	}
}
